package com.pvdnc.tapkit.utils;

import com.pvdnc.nsocket.log.SLog;
import com.pvdnc.tapkit.utils.encrypt.AESKeyUtils;
import com.pvdnc.tapkit.utils.encrypt.MD5;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;



public class AESUtils{
    private static final SLog LOG=new SLog(AESUtils.class);

    private final static String HEX = "0123456789ABCDEF";
    private  static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";//AES是加密方式 CBC是工作模式 PKCS5Padding是填充模式
    private  static final String AES = "AES";//AES 加密
    private  static final String  SHA1PRNG="SHA1PRNG";//// SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法

    private static byte[] encrypt(byte[] clear,byte[] rawKey) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(clear);
    }

    private static byte[] decrypt(byte[] encrypted,byte[] rawKey) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(rawKey, AES);
        Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(encrypted);
    }

    public static void main(String[] args) throws Exception {
        System.out.println("ac43776ddb184d94683fe9e502b52796".length());
        byte[] md5Data= MD5.MD5("233").getBytes();
        System.out.println(md5Data.length);
        //AES
        byte[] content = "1111111111111111".getBytes();
        byte[] key = AESKeyUtils.create("password".getBytes()).getEncoded();
        byte[] s1 = AESUtils.encrypt(content, key);
        System.out.println("s1:" + new String(s1));
        byte[] decryptedContent=AESUtils.decrypt(s1, key);
        System.out.println("s2:"+new String(decryptedContent));
    }

}

